<?php

class InfoController extends MemberBaseController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/member';

	
	//验证码
	public function actions()
	{
		return array(
				// captcha action renders the CAPTCHA image displayed on the contact page
				'captcha'=>array(
						'class'=>'CCaptchaAction',
						'backColor'=>0xFFFFFF,
						'minLength'=>4,  //最短为4位
						'maxLength'=>4,   //是长为4位
						'height'=>'35',
						'width'=>'100',
						'padding'=>'0',
				),
				// page action renders "static" pages stored under 'protected/views/site/pages'
				// They can be accessed via: index.php?r=site/page&view=FileName
				'page'=>array(
						'class'=>'CViewAction',
				),
		);
	}

	
	/**
	 * 修改会员资料
	 * 
	 */
	public function actionInfo()
	{
		$id = isset(Yii::app()->user->userid)?Yii::app()->user->userid:'';
		if(!$id){
			$this->redirect('/home/user/login');
		}
		$model_main = $this->loadModel($id);
		//print_r($model_main->attributes);
		$model_more = MemPro::model()->find('zm_id='.$id);
		$model_more = $model_more ? $model_more : new MemPro();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Member']) && isset($_POST['MemPro']) )
		{
			if($_POST['Member']['zm_id'] !== $id || $_POST['MemPro']['zm_id'] !== $id){
				//请求超时
				$this->refresh();
			}
			$model_main->attributes=$_POST['Member'];
			$model_main->updatetime = time();
			$model_more->attributes=$_POST['MemPro'];
			$model_more->zmp_birthday = strtotime($_POST['MemPro']['zmp_birthday']);			
			//echo $model_main->validate(),2222,$model_more->validate();
			if($model_more->validate()){
			//if($model_main->validate() && $model_more->validate()){
				//主表有字段时需开启下面这行
				//$model_main->save(false);

				$model_more->save(false);
				$model_main->setUserInfo();
				$this->render('../index/success',array('message'=>'修改会员资料成功'));
				exit;
			}else{
				//提示验证失败
				$this->render('../index/error',array('message'=>'修改会员资料失败'));
				//echo $model_main->getErrorsStr();
				//echo $model_more->getErrorsStr();
				Yii::app()->end();
			}
		}
		//print_r($model_more->attributes);
		//echo $model_more->getErrorsStr();exit;
		$model_more->zmp_birthday = date('Y-m-d',$model_more->zmp_birthday);
		$this->render('info',array('model_main'=>$model_main,'model_more'=>$model_more));
	}

	//更换头像
	public function actionFace(){
		$model=Member::model()->findByPk(Yii::app()->user->userid);
		if(isset($_POST['Member']))
		{
			$model->zm_face = $_POST['Member']['zm_face'];
			$image = CUploadedFile::getInstance($model, 'zm_face');
			$name = time().rand(11111,99999);
			$path = Yii::app()->params['uploadPath'].'/faces/'.date('Ymd');
			$path = substr($path,1);
			if(!file_exists($path)){
				mkdir($path);
			}
			if( is_object($image) && get_class($image) === 'CUploadedFile' ){
				$model->zm_face = $path.'/'.$name.'_320.'.$image->extensionName;
				$small = $path.'/'.$name.'_100.'.$image->extensionName;
				Yii::app()->user->setState('face' , $model->zm_face);
				if( $model->update('zm_face='.$model->zm_face) ){
					$face = Yii::app()->image->load($image->tempName );
					$face->resize(320,320)->quality(85);
					$face->save($model->zm_face);
					$face->resize(100,100)->quality(85);
					$face->save($small);
				}
			}
		}
		$this->render('info_face',array('model'=>$model,));
	}

	//会员等级
	public function actionLevel(){
		$model=Member::model()->findByPk(Yii::app()->user->userid);
		$this->render('info_level',array('model'=>$model,));
	}

	/**
	 * 修改会员登录密码或支付密码
	 *
	 */
public function actionRepass()
	{
		$id = isset(Yii::app()->user->userid)?Yii::app()->user->userid:'';
		if(!$id){
			$this->redirect('/home/user/login');
		}
		$model = $this->loadModel($id);
		//设置当前情况下的验证场景
		$model->scenario = 'forgot';
		if(isset($_POST['ajax']) && $_POST['ajax']==='member-form'){
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		$type = isset($_POST['Member']['type']) ? $_POST['Member']['type'] : '';
		if( isset($_POST['Member']) && in_array($type,array('psword','paypsword')) && !empty($_POST['Member']['zm_'.$type]))
		{
			if($type == 'paypsword'){
				$captcha = $_POST['Member']['captcha'];
				if(!$model->checkEmailCaptcha($captcha)){
					$this->render('../index/error',array('message'=>'验证码错误，请重试!')  
                    );  
                 exit;	
				}
			}
			if( $_POST['Member']['zm_id'] !== $id ){
				//请求超时
				$this->refresh();
			}
			$type = $_POST['Member']['type'];
			$field = 'zm_'.$type;
			$code = $type=='psword' ? 1 : 2; //$code：加密解密识别码，1为登录密码，2为支付密码
			
			/* if( $_POST['Member']['zm_'.$type] != $_POST['Member']['re_'.$type] ){
				$this->render('../index/error',array('message'=>'两次输入密码不同!请重新输入！')  
                    );  
                 exit;
			} */
			 if( !$model->checkPassword( $_POST['Member']['old_psword'] , $code ) ){
				$this->render('../index/error',array('message'=>'原密码不对，请重新输入！')  
                    );  
                 exit;				
			}
			
			$model->$field = $model->passwordEncode( $_POST['Member'][$field] , $code ); 
			if($model->save(false)){
				//修改成功
				 $this->render('../index/success',array('message'=>'修改支付密码成功!')  
                    );  
                 exit;
                    
			}else{
				//修改失败
				 $this->render('../index/error',array('message'=>'修改支付密码失败!')  
                    );  
                 exit;
			}
		}		
		//echo $model_more->getErrorsStr();exit;
		$this->render('security',array('model'=>$model));
	}


	/**
	 * 修改会员邮箱
	 *
	 */
	public function actionChangeEmail()
	{		
		$id = isset(Yii::app()->user->userid)?Yii::app()->user->userid:'';
		if(!$id){
			$this->redirect('/home/user/login');
		}
		$model = $this->loadModel($id);
		if( isset($_POST['Member']['zm_email']) && isset($_POST['Member']['captcha']) )
		{
			$captcha = $_POST['Member']['captcha'];
			if(!$model->checkEmailCaptcha($captcha)){
				 $this->render('../index/error',array('message'=>'验证码错误，请重试!')  
                    );  
                 exit;				
			}
			if( $_POST['Member']['zm_id'] !== $id ){
				//请求超时
				$this->refresh();
			}
			if( $_POST['Member']['zm_email'] == $model->zm_email ){
				//请求超时
				$this->render('../index/error',array('message'=>'输入邮箱和原邮箱相同，请检查!')  
                    );  
                 exit;
			}
			
			$model->zm_email = $_POST['Member']['zm_email'];
			
			if($model->validate(array('zm_email'))){
				$conditions = 'zm_email=:email';
				$params = array(':email'=>$model->zm_email);
				if($model->exists($conditions,$params)){
					exit('this email already exists!');
				}
				$model->zm_check_status = $model->zm_check_status == 4 ? 3 : 1;
				if($model->save(false)){
					Yii::app()->user->setState('email',$model->zm_email);
					//发送激活邮件....
					$url = $model->createActivateUrl();
					$mailer = Yii::app()->mailer;
					if(Yii::app()->params['mailType'] == 'smtp'){					
						$mailer->IsSMTP();
						$mailer->SMTPAuth = true;
					}
					$mailer->AddReplyTo($model->zm_email);
					$mailer->AddAddress($model->zm_email);
					$mailer->Subject = F::setting('sitename').'用户邮箱激活';
					$params = array('username'=>$model->zm_name,'url'=>$url);
					$mailer->getView('activate', array('params'=>$params,'mailer'=>$mailer),'member');
					$mailer->Send();
					
					$this->render('../index/error',array('message'=>'成功发送激活邮件!请登录你的邮箱激活Email!')  
                    );  
                 	exit;                 
					
				}
			}else{
				//格式错误
				$this->render('../index/error',array('message'=>'格式错误')  
                    );  
                exit;  
			}
		}		
		//echo $model_more->getErrorsStr();exit;
		$this->render('security',array('model'=>$model));
	}
	

	/**
	 * 我的积分
	 */
	public function actionMyPoints()
	{
		$point     = Member::model()->findByPk(Yii::app()->user->userid)->zm_value;
		$model =PointLog::model();
		$this->render('point',array(
			'model'=>$model,
			'point'=>$point,
		));
	}
	
	/**
	 * 我的优惠券
	 */
	public function actionMyCoupons()
	{
		$model   = MemTicket::model();
		$amounts = Ticket::model()->amountOfStatus(Yii::app()->user->userid);
		//print_r($amounts);exit;
		$this->render('mycoupons',array(
			'model'=>$model,
			'amounts'=>$amounts,
		));
	}
	
	/**
	 * 已使用优惠券
	 */
	public function actionUsedCoupons()
	{
		$model=new TicketLog();
		$amounts = Ticket::model()->amountOfStatus(Yii::app()->user->userid);
		$this->render('usedcoupons',array(
			'model'=>$model,
			'amounts'=>$amounts,
		));
	}
	
	/**
	 * 查看优惠券
	 */
	public function actionViewCoupon()
	{

	}
	
	/**
	 * 删除优惠券
	 */
	public function actionDeleteMemCoupon()
	{
		$ids = Yii::app()->request->getParam('ids',0);
		$idbox = array(0);
		if(is_array($ids) && count($ids)){
			foreach($ids as $key=>$id){
				(int)$id && $idbox[] = (int)$id;
			}
		}elseif($ids){
			(int)$ids && $idbox[] = (int)$ids;
		}else{
			$message = '删除失败，未选中任何选项。';
			$path = '../index/error';
		}
		if(count($idbox)>1 && MemTicket::model()->deleteMemTicket($idbox, Yii::app()->user->userid)){
			$message = '删除成功。';
			$path = '../index/success';
		}elseif(count($idbox)>1){
			$message = '删除失败。';
			$path = '../index/error';
		}
		$this->render($path,array('message'=>$message)  
                    ); 
		//echo '<script>if(confirm("'.$message.'")){self.history.back();}</script>';
	}
	
	/**
	 * 优惠券中心
	 */
	public function actionCouponsCenter()
	{
		$model=new Ticket();
		$amounts = Ticket::model()->amountOfStatus(Yii::app()->user->userid);
		$this->render('couponscenter',array(
				'model'=>$model,
				'amounts'=>$amounts,
		));
	}
	
	/**
	 * 领取优惠券
	 */
	public function actionGetCoupon()
	{
		$amount = (int)Yii::app()->request->getParam('amount',0);
		$id = (int)Yii::app()->request->getParam('zti_id',0);
		if( $amount && $id ){
			$iflimit = Ticket::model()->checkLimit(Yii::app()->user->userid,$id,$amount);
			if(!$iflimit){
				//优惠券数据
				$ticket    = Ticket::model()->findByPk($id);
				$ticket->zti_inventory  -= $amount;
				//会员优惠券数据
				$memTicket = MemTicket::model()->find('zm_id=:memberid and zti_id=:ticketid and zmi_status=:status',array(':memberid'=>Yii::app()->user->userid,':ticketid'=>$id,':status'=>1));
				if($memTicket){
					$memTicket->zmi_num += $amount;
					$memTicket->inputtime      = time();
				}else{
					$memTicket = new MemTicket();
					$memTicket->zm_id          = Yii::app()->user->userid;
					$memTicket->zti_id         = $id;
					$memTicket->zmi_status     = 1;
					$memTicket->zmi_val        = $ticket->zti_value;
					$memTicket->zmi_num        = $amount;
					//$memTicket->zmi_title      = $ticket->zti_title;
					$memTicket->zmi_start_time = $ticket->zti_start_time;
					$memTicket->zmi_end_time   = $ticket->zti_end_time;
					$memTicket->inputtime      = time();
				}
				//优惠券日志数据
				$ticketLog = new TicketLog();
				$ticketLog->zm_id     = Yii::app()->user->userid;
				$ticketLog->zti_id    = $id;
				$ticketLog->ztl_num   = $amount;
				$ticketLog->ztl_price = $ticket->zti_value;
				$ticketLog->inputtime = time();
				//事务
				$transaction= Yii::app()->db->beginTransaction();
				try
				{
					$ticket->save();
					$memTicket->save();
					$ticketLog->save();
					$transaction ->commit( ) ;
				}
				catch ( Exception  $e)
				{
					$transaction ->rollBack( ) ;
					$this->render('../index/error',array('message'=>'领取失败')  
                    );  
                	exit; 					
				}
				$this->render('../index/success',array('message'=>'领取成功')  
                    );  
                exit;                
			}else{
				$this->render('../index/error',array('message'=>'没有这个优惠券')  
                    );  
                exit;				
			}
		}
	}


	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Member('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Member']))
			$model->attributes=$_GET['Member'];
	
		$this->render('admin',array(
				'model'=>$model,
		));
	}

	/**
	 * 根据ID返回用户实例
	 */
	public function loadModel($id)
	{	
		
		$model=Member::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * 执行AJAX异步验证.
	 * @param CModel 要验证的模型
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='member-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
